﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using CustomControls;
using Model.EntityModel;
using DataAccess;
using System.Collections.ObjectModel;

namespace Project
{
    /// <summary>
    /// Interaction logic for RegisterCitationContent.xaml
    /// </summary>
    public partial class RegisterCitationContent : UserControl
    {
        public long idComplaint;
        String Hours;
        String Minutes;
        Actor ActorDenounced = new Actor();
        Person Denounced = new Person();
        Actor ActorAggressor = new Actor();
        Person Aggressor = new Person();
        Employee functionary = new Employee();
        Model.Functionary f = new Model.Functionary();
        SearchFunctionary search;
        SearchComplaintWindow sc;
        Citation citation = new Citation();

        

        public RegisterCitationContent()
        {
            InitializeComponent();
            UIWindowManager.SetWindowTitle(this,"Brigada De Protección a la Familia - Registrar Citación");
            TxtBoxAggressorMName.DeactivateBlankValidation();
            TxtBoxDenouncedMName.DeactivateBlankValidation();
            TxtBoxemployeeMName.DeactivateBlankValidation();
            datePickerCitationDate.DisplayDateStart = DateTime.Now;
            datePickerCitationDate.DisplayDateEnd = DateTime.Now.AddMonths(10);
        }

        public void Charge()
        {
            try
            {
                ActorDenounced = PersonAndActorDataAccess.GetActorByTypeAndComplaintId("Denunciante", idComplaint);
                Denounced = PersonAndActorDataAccess.GetPersonById(ActorDenounced.IdPerson);
                ActorAggressor = PersonAndActorDataAccess.GetActorByTypeAndComplaintId("Agresor", idComplaint);
                Aggressor = PersonAndActorDataAccess.GetPersonById(ActorAggressor.IdPerson);
                TxtBoxDenouncedName.Text = Denounced.Name.ToString();
                TxtBoxDenouncedPName.Text = Denounced.PaternalName;
                TxtBoxDenouncedMName.Text = Denounced.MaternalName;
                TxtBoxAggressorName.Text = Aggressor.Name;
                TxtBoxAggressorPName.Text = Aggressor.PaternalName;
                TxtBoxAggressorMName.Text = Aggressor.MaternalName;
            }
            catch
            {
                Xceed.Wpf.Toolkit.MessageBox.Show("Error en al obtener datos de nuestra base de datos", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            
            
        }

        private bool CheckHasErrors()
        {
            bool res = false;
           
                    foreach (var ctrl in (Content as Grid).Children)
                    {
                        TextBox tb = ctrl as TextBox;
                        if (tb != null)
                        {
                            tb.GetBindingExpression(TextBox.TextProperty).UpdateSource();
                            if (Validation.GetHasError(tb))
                                res = true;
                        }
                        ValidationComboBox cb = ctrl as ValidationComboBox;
                        if (cb != null)
                        {
                            cb.LostFocusEventHandler(cb, null);
                            if (Validation.GetHasError(cb))
                                res = true;
                        }
                        ValidDatePicker dtp = ctrl as ValidDatePicker;
                        if (dtp != null)
                        {
                            dtp.GetBindingExpression(DatePicker.TextProperty).UpdateSource();
                            dtp.LostFocusEventHandler(dtp, null);
                            if (Validation.GetHasError(dtp))
                                res = true;
                        }
            }
            return res;
        }

        private void cmbBoxHours_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cmbBoxHours.SelectedIndex != -1)
            {
                ComboBoxItem item = (ComboBoxItem)cmbBoxHours.SelectedValue;
                Hours = item.Content.ToString();
            }
        }

        private void cmbBoxMinutes_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cmbBoxMinutes.SelectedIndex != -1)
            {
                ComboBoxItem item = (ComboBoxItem)cmbBoxMinutes.SelectedValue;
                Minutes = item.Content.ToString();
            }
        }

        void getEmployeeEventHandler(object sender, RoutedEventArgs e)
        {
            try
            {
                functionary.CI = search.Employee.CI;
                f = DataBaseAccess.ReadEmployee(functionary.CI);
                functionary.Name = f.Name;
                functionary.PaternalName = f.PaternalName;
                functionary.MaternalName = f.MaternalName;
                functionary.Rank = f.Rank;
                search.Close();
              
                TxtBoxEmployeeName.Text = functionary.Name;
                TxtBoxEmployeePName.Text = functionary.PaternalName;
                TxtBoxemployeeMName.Text = functionary.MaternalName;
                TxtBoxEmployeRank.Text = functionary.Rank;
            }
            catch
            {
                Xceed.Wpf.Toolkit.MessageBox.Show("Ocurrio un error al obtener el empleado", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        void getComplaintEventHandler(object sender, RoutedEventArgs e)
        {
            try
            {
                idComplaint = (sc.Content.Children[0] as SearchComplaint).SelectedComplaintId;
                lblCaseNumber.Content = idComplaint;
                Charge();
            }
            catch
            {
                Xceed.Wpf.Toolkit.MessageBox.Show("Ocurrio un error al obtener el empleado", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

       
        private void TxtBoxEmployeRank_GotFocus(object sender, RoutedEventArgs e)
        {
            search = new SearchFunctionary();
            search.getEmployee += new RoutedEventHandler(getEmployeeEventHandler);
            search.ShowDialog();
            TxtBoxEmployeRank.Focusable = false;
        }

        private void TxtBoxEmployeeName_GotFocus(object sender, RoutedEventArgs e)
        {
            TxtBoxEmployeRank_GotFocus(sender, e);
            TxtBoxEmployeeName.Focusable = false;
        }

        private void BtnSave_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (!CheckHasErrors())
                {
                    
                        citation.CitationDate = datePickerCitationDate.SelectedDate;
                        TimeSpan time=new TimeSpan(Convert.ToInt32(Hours), Convert.ToInt32(Minutes),0);
                        citation.CitationTime = time;
                        citation.IdComplaint = idComplaint;
                        citation.IdEmployee = functionary.CI;
                        List<Citation> exist = CitationDataAccess.GetCitationsByComplaint(idComplaint);
                        if (exist.Count < 3)
                        {
                            citation = CitationDataAccess.InsertCitation(citation);
                            MessageBoxResult result = MessageBox.Show("Citacion Registrada! Desea imprimirla?", "Informacion", MessageBoxButton.YesNo, MessageBoxImage.Question);
                            if (result == MessageBoxResult.Yes)
                            {
                                var items = new ObservableCollection<UserControl>();
                                items.Add(new PrintCitation(idComplaint, citation.Id));
                                var a = new PrintPreviewDialogV2(items);
                                a.ShowDialog();
                            }
                            else
                            {
                                Xceed.Wpf.Toolkit.MessageBox.Show("Puede imprimir la citacion posteriormente, entrando a Ver Denuncias, click sobre la denuncia selecciona la opción Ver Citaciones seleccionando por fecha la citacion que desea",
                                                                "Información!", MessageBoxButton.OK, MessageBoxImage.Information);
                            }
                            UIWindowManager.CleanWindow(this);
                        }
                        else
                        {
                            Xceed.Wpf.Toolkit.MessageBox.Show("Ya existen tres citaciones registradas", "Advertencia", MessageBoxButton.OK, MessageBoxImage.Warning);
                            UIWindowManager.CleanWindow(this);
                        }
                }
            }
            catch
            {
                Xceed.Wpf.Toolkit.MessageBox.Show("La operacion no puede completarse", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

       

       
        private void TxtBoxDenouncedName_GotFocus(object sender, RoutedEventArgs e)
        {
            sc = new SearchComplaintWindow();
            (sc.Content.Children[0] as SearchComplaint).listViewComplaints.MouseDoubleClick += (getComplaintEventHandler);
            sc.ShowDialog();
            TxtBoxDenouncedName.Focusable=false;
        }

        private void TxtBoxDenouncedPName_GotFocus(object sender, RoutedEventArgs e)
        {
            TxtBoxDenouncedName_GotFocus(sender, e);
            TxtBoxDenouncedPName.Focusable = false;
        }

        private void TxtBoxDenouncedMName_GotFocus(object sender, RoutedEventArgs e)
        {
            TxtBoxDenouncedName_GotFocus(sender, e);
            TxtBoxDenouncedMName.Focusable = false;
        }

        private void TxtBoxAggressorName_GotFocus(object sender, RoutedEventArgs e)
        {
            TxtBoxDenouncedName_GotFocus(sender, e);
            TxtBoxAggressorName.Focusable = false;
        }

        private void TxtBoxAggressorPName_GotFocus(object sender, RoutedEventArgs e)
        {
            TxtBoxDenouncedName_GotFocus(sender, e);
            TxtBoxAggressorPName.Focusable = false;
        }

        private void TxtBoxAggressorMName_GotFocus(object sender, RoutedEventArgs e)
        {
            TxtBoxDenouncedName_GotFocus(sender, e);
            TxtBoxAggressorMName.Focusable = false;
        }

        private void TxtBoxEmployeePName_GotFocus(object sender, RoutedEventArgs e)
        {
            TxtBoxEmployeRank_GotFocus(sender, e);
            TxtBoxEmployeePName.Focusable = false;
        }

        private void TxtBoxemployeeMName_GotFocus(object sender, RoutedEventArgs e)
        {
            TxtBoxEmployeRank_GotFocus(sender, e);
            TxtBoxemployeeMName.Focusable = false;
        }

       
    }
}
